package com.pospi.util;

import android.content.Context;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lany.sp.SPHelper;
import com.pospi.dto.GoodsDto;
import com.pospi.pai.yunpos.login.Constant;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import sunmi.ds.DSKernel;
import sunmi.ds.callback.ICheckFileCallback;
import sunmi.ds.callback.IConnectionCallback;
import sunmi.ds.callback.ISendCallback;
import sunmi.ds.callback.ISendFilesCallback;
import sunmi.ds.callback.QueryCallback;
import sunmi.ds.data.DSData;
import sunmi.ds.data.DataPacket;

/**
 * Created by acer on 2018/8/30.
 * 副屏开发
 */

public class SumiUtil {
    private Context context;
    private DSKernel mDSKernel = null;
    private final String TAG = "sumi";
    private List<String> products = new ArrayList<>();
    private List<String> prices = new ArrayList<>();
    private List<GoodsDto> dtos = new ArrayList<>();
    /**
     * 轮播图集合
     * slide collection
     */
    List<String> imgs = new ArrayList<>();
    private IConnectionCallback mIConnectionCallback = new IConnectionCallback() {
        @Override
        public void onDisConnect() {

        }

        @Override
        public void onConnected(ConnState state) {

        }
    };

    public SumiUtil(Context context) {
        this.context = context;
        initSdk();
        initImges();
    }

    private void initSdk() {
        mDSKernel = DSKernel.newInstance();
        mDSKernel.init(context, mIConnectionCallback);
    }

    public void initImges() {
        imgs.clear();
        imgs.add(Environment.getExternalStorageDirectory().getPath() + "/01.png");
        imgs.add(Environment.getExternalStorageDirectory().getPath() + "/02.png");

    }

    public void initImgesMenus(List<GoodsDto> dtos) {
        imgs.clear();
        String urls = SPHelper.getInstance().getString(Constant.IMG_LOCAL, "");
        List<String> imgList;
        if (urls.isEmpty()) {
            imgList = getPictures("");
        } else {
            imgList = new Gson().fromJson(urls, new TypeToken<List<String>>() {
            }.getType());
        }
        if (imgList != null) {
            for (String s : imgList) {
                imgs.add(s);
                Log.i("img", s);
            }
        }

//        imgs.add(Environment.getExternalStorageDirectory().getPath() + "/01.png");
//        imgs.add(Environment.getExternalStorageDirectory().getPath() + "/02.png");
//        imgs.add(Environment.getExternalStorageDirectory().getPath() + "/03.png");
//        imgs.add(Environment.getExternalStorageDirectory().getPath() + "/04.png");
//        imgs.add(Environment.getExternalStorageDirectory().getPath() + "/05.png");
        this.dtos = dtos;
    }
    public void sendSinglePicture() {
        Log.d(TAG, "sendPicture: --------->1111111111111111111");
        mDSKernel.sendFile(DSKernel.getDSDPackageName(), Environment.getExternalStorageDirectory().getPath() + "/img01.png", new ISendCallback() {
            @Override
            public void onSendSuccess(long taskId) {
                SPHelper.getInstance().putLong(Constant.IMG_KEY, taskId);
                Log.d(TAG, "sendPicture: --------->222222222222222222");
                showPicture(taskId);
            }

            @Override
            public void onSendFail(int errorId, String errorInfo) {
                Log.d("TAG", "onSendFail: -------------------->" + errorId + "  " + errorInfo);
            }

            @Override
            public void onSendProcess(long totle, long sended) {
                Log.d(TAG, "sendPicture: --------->"+totle+"  "+sended);
            }
        });
    }

    /**
     * 展示单张图片
     *
     * @param taskId
     */
    private void showPicture(long taskId) {
        //显示图片
        try {
            JSONObject json = new JSONObject();
            json.put("dataModel", "SHOW_IMG_WELCOME");
            json.put("data", "default");
            mDSKernel.sendCMD(DSKernel.getDSDPackageName(), json.toString(), taskId, new ISendCallback() {
                @Override
                public void onSendSuccess(long taskId) {
                    Log.d(TAG, "sendPicture: --------->33333333333333");
                }

                @Override
                public void onSendFail(int errorId, String errorInfo) {

                }

                @Override
                public void onSendProcess(long totle, long sended) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    /**
     * 发送轮播图片
     */
    public void sendImgs() {
        JSONObject json = new JSONObject();
        try {
            //轮播图切换时间
            json.put("rotation_time", 2000);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        mDSKernel.sendFiles(DSKernel.getDSDPackageName(), json.toString(), imgs, new ISendFilesCallback() {
            @Override
            public void onAllSendSuccess(long l) {
                Log.d("TAG", "onAllSendSuccess: ---------->");
                showImgs(l);
                SPHelper.getInstance().putLong(Constant.IMG_KEY, l);
            }

            @Override
            public void onSendSuccess(final String path, final long fileId) {
                Log.d("TAG", "onSendSuccess: ----------->");
            }

            @Override
            public void onSendFaile(final int i, final String s) {
                Log.d("TAG", "onSendFaile: ------------->" + s);

            }

            @Override
            public void onSendFileFaile(String s, int i, String s1) {
                Log.d(TAG, "onSendFileFaile: --------------->" + s + "  " + s1);

            }

            @Override
            public void onSendProcess(final String s, final long l, final long l1) {
                Log.d(TAG, "onSendProcess: ----------->" + s + "  " + l + "  " + l1);
            }
        });
    }
    /**
     * 检查轮播图缓存文件是否存在
     *
     * @param taskID
     */
    private void checkImgsFileExist(final long taskID) {
        if (taskID < 0) {
            sendImgs();
            return;
        }
        checkFileExist(taskID, new ICheckFileCallback() {
            @Override
            public void onCheckFail() {
                //检查缓存文件失败
                Log.d(TAG, "onCheckFail: ------------>file not exist");
                sendImgs();
            }

            @Override
            public void onResult(boolean exist) {
                if (exist) {
                    //缓存文件存在
                    Log.d(TAG, "onResult: --------->file is exist");
                    showImgs(taskID);
                } else {
                    //缓存文件不存在
                    sendImgs();
                }
            }
        });
    }


    /**
     * 展示轮播图片
     */
    private void showImgs(long taskId) {
        String json = UPacketFactory.createJson(DataModel.IMAGES, "");
        mDSKernel.sendCMD(DSKernel.getDSDPackageName(), json, taskId, null);
    }
    private void checkFileExist(long fileId, final ICheckFileCallback mICheckFileCallback) {
        DataPacket packet = new DataPacket.Builder(DSData.DataType.CHECK_FILE).data("def").
                recPackName(DSKernel.getDSDPackageName()).addCallback(new ISendCallback() {
            @Override
            public void onSendSuccess(long taskId) {

            }

            @Override
            public void onSendFail(int errorId, String errorInfo) {
                if (mICheckFileCallback != null) {
                    mICheckFileCallback.onCheckFail();
                }
            }

            @Override
            public void onSendProcess(long totle, long sended) {

            }
        }).isReport(true).build();
        packet.getData().fileId = fileId;
        mDSKernel.sendQuery(packet, new QueryCallback() {
            @Override
            public void onReceiveData(DSData data) {
                boolean exist = TextUtils.equals("true", data.data);
                if (mICheckFileCallback != null) {
                    mICheckFileCallback.onResult(exist);
                }
            }
        });
    }

    public void sendImgsMenu() {
        mDSKernel.sendFiles(DSKernel.getDSDPackageName(), "", imgs, new ISendFilesCallback() {
            @Override
            public void onAllSendSuccess(long fileId) {
                showImgsMenu(fileId);
                SPHelper.getInstance().putLong(Constant.IMG_KEY, fileId);
            }

            @Override
            public void onSendSuccess(String path, long taskId) {

            }

            @Override
            public void onSendFaile(int errorId, String errorInfo) {

            }

            @Override
            public void onSendFileFaile(String path, int errorId, String errorInfo) {

            }

            @Override
            public void onSendProcess(String path, long totle, long sended) {
            }
        });
    }

    private void showImgsMenu(long taskId) {

        double hjje = 0;
        double yhje = 0;
        double sl = 0;
        double ysje = 0;
        final JSONObject data = new JSONObject();
        try {

            data.put("title", "X-STORE");
            JSONObject head = new JSONObject();
            head.put("param1", "序号");
            head.put("param2", "商品名");
            head.put("param3", "单价");
            head.put("param4", "数量");
            head.put("param5", "小结");
            data.put("head", head);
            data.put("alternateTime", 5000);
            JSONArray list = new JSONArray();
            for (int i = 0; i < dtos.size(); i++) {
                GoodsDto dto = dtos.get(i);
                hjje += dto.getPrice() * dto.getNum();
                yhje += dto.getDiscount();
                sl += dto.getNum();
                ysje += dto.getPrice() * dto.getNum() - dto.getDiscount();

                JSONObject listItem = new JSONObject();
                listItem.put("param1", String.valueOf(i+1));
                listItem.put("param2", dto.getName() );
                listItem.put("param3", String.valueOf(dto.getPrice()));
                listItem.put("param4", String.valueOf(dto.getNum()));
                listItem.put("param5", String.valueOf(DoubleSave.doubleSaveTwo(dto.getPrice() * dto.getNum() - dto.getDiscount())));
                list.put(listItem);
            }
            data.put("list", list);
            JSONArray KVPList = new JSONArray();
            JSONObject KVPListOne = new JSONObject();
            KVPListOne.put("name", "总计 ");
            KVPListOne.put("value", String.valueOf(DoubleSave.doubleSaveTwo(hjje)));
            JSONObject KVPListTwo = new JSONObject();
            KVPListTwo.put("name", "优惠 ");
            KVPListTwo.put("value", String.valueOf(DoubleSave.doubleSaveTwo(yhje)));
            JSONObject KVPListThree = new JSONObject();
            KVPListThree.put("name", "数量 ");
            KVPListThree.put("value", String.valueOf(DoubleSave.doubleSaveTwo(sl)));
            JSONObject KVPListFour = new JSONObject();
            KVPListFour.put("name", "应收 ");
            KVPListFour.put("value", String.valueOf(DoubleSave.doubleSaveTwo(ysje)));

            KVPList.put(0, KVPListOne);
            KVPList.put(1, KVPListTwo);
            KVPList.put(2, KVPListThree);
            KVPList.put(3, KVPListFour);
            data.put("KVPList", KVPList);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String json1 = UPacketFactory.createJson(DataModel.SHOW_IMGS_LIST, data.toString());
        mDSKernel.sendCMD(DSKernel.getDSDPackageName(), json1, taskId, null);
    }

    public void checkImgsMenuExists(final long taskId) {
        if (taskId < 0) {
            sendImgsMenu();
            return;
        }
        checkFileExist(taskId, new ICheckFileCallback() {
            @Override
            public void onCheckFail() {
                Log.d(TAG, "onCheckFail: ------->file is not exist");
                sendImgsMenu();
            }

            @Override
            public void onResult(boolean exist) {
                if (exist) {
                    Log.d(TAG, "onResult: ---------->file is exist");
                    showImgsMenu(taskId);
                } else {
                    Log.d(TAG, "onResult: --------->file is not exists");
                    sendImgsMenu();
                }
            }
        });
    }
    public void clear(){
        DataPacket packet2 = UPacketFactory.remove_folders(DSKernel.getDSDPackageName(), Environment.getExternalStorageDirectory().getAbsolutePath() + "/HCService/" + context.getPackageName().replace(".", "_"), new ISendCallback() {
            @Override
            public void onSendSuccess(long taskId) {
            }
            @Override
            public void onSendFail(int errorId, String errorInfo) {

            }
            @Override
            public void onSendProcess(long totle, long sended) {

            }
        });
        mDSKernel.sendCMD(packet2);
    }


    public List<String> getPictures(final String strPath) {
        List<String> list = new ArrayList<String>();
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+strPath);
        File[] allfiles = file.listFiles();
        if (allfiles == null) {
            return null;
        }
        for(int k = 0; k < allfiles.length; k++) {
            final File fi = allfiles[k];
            if(fi.isFile()) {
                int idx = fi.getPath().lastIndexOf(".");
                if (idx <= 0) {
                    continue;
                }
                String suffix = fi.getPath().substring(idx);
                if (suffix.toLowerCase().equals(".jpg") ||
                        suffix.toLowerCase().equals(".jpeg") ||
                        suffix.toLowerCase().equals(".bmp") ||
                        suffix.toLowerCase().equals(".png") ||
                        suffix.toLowerCase().equals(".gif") ) {
                    list.add(fi.getPath());
                }
            }
        }
        return list;
    }


}
